using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.IO;
using System.Windows.Forms;
using System.Xml;

namespace Weathertastic
{
    public partial class LocationPicker : Form
    {
        private delegate void DownloadDelegate();
        private delegate void UpdateListViewDelegate(XmlNode _node);
        private delegate void ClearListViewDelegate();
        private delegate void SelectListViewItemDelegate(int index);
        private delegate void StopSpinnerDelegate();

        private string _location = string.Empty;
        private string _downloadString = string.Empty;
        private DownloadFile _fileDownload = null;
        //private Error _error = new Error();
        private XmlDocument xFile = null;
        private Settings _settings = new Settings();

        private int _listSelected = -1;

        public LocationPicker()
        {
            InitializeComponent();

            this.Icon = Icon.FromHandle(((Bitmap)Image.FromFile("images/settings.png")).GetHicon());
            _downloadString = "http://xoap.weather.com/search/search?where=";

        }


        private void LocationPicker_Load(object sender, EventArgs e)
        {
            _fileDownload = new DownloadFile();

        }

        private void GetLocations(string location)
        {
            _location = location;
            //spinner.Visible = true;
            //spinner.Active = true;
            DownloadDelegate del = new DownloadDelegate(DownloadLocations);
            del.BeginInvoke(new AsyncCallback(OnDownloadedLocations), null);
        }


        private void DownloadLocations()
        {
            if (_fileDownload == null)
                _fileDownload = new DownloadFile();

            if (_location != string.Empty)
            {
                _fileDownload.Download(_downloadString + _location, "location_search.xml");
                _fileDownload = null;
            } // Location string is not empty;
        }

        private void OnDownloadedLocations(IAsyncResult ar)
        {
            UpdateListView();
        }

        private void UpdateListView()
        {
            try
            {
                //TODO: Checks on array sizes, if results exist
                ClearListViewDelegate clv = new ClearListViewDelegate(ClearListViewMethod);
                listView1.Invoke(clv);

                    xFile = new XmlDocument();
                    xFile.Load("location_search.xml");
                    XmlNodeList _nodes = xFile.SelectNodes("//loc");
                    for (int i = 0; i < _nodes.Count; i++)
                    {
                        UpdateListViewDelegate ud = new UpdateListViewDelegate(UpdateListViewMethod);
                        listView1.Invoke(ud, new object[] { _nodes[i] });
                        ud = null;
                    }
                    
                    _nodes = null;
                    xFile = null;

                    if (_listSelected > -1)
                    {
                        SelectListViewItemDelegate sd = new SelectListViewItemDelegate(SelectListViewItemMethod);
                        listView1.Invoke(sd, new object[] { _listSelected });
                    }
                }

                catch (Exception exc)
                {
                    throw;
                }
        }

        private void StopSpinnerMethod()
        {
            //spinner.Active = false;
            //spinner.Visible = false;
        }

        private void SelectListViewItemMethod(int index)
        {
            if (index > -1)
            {
                listView1.Items[index].Selected = true;
            }

        }

        private void UpdateListViewMethod(XmlNode nodeIn)
        {
            ListViewItem _item = new ListViewItem(nodeIn.InnerText);

            string _stationCode = nodeIn.Attributes[0].Value;
            _item.Tag = _stationCode;
            listView1.Items.Add(_item);

            if (_stationCode.Equals(_settings.StationCode))
                _listSelected = listView1.Items.Count - 1;



        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            if (textSearch.Text != string.Empty)
            {
                _location = textSearch.Text;
                GetLocations(_location);
            }
        }


        private void ClearListViewMethod()
        {
            listView1.Items.Clear();
        }

        public void SaveLocation()
        {
            if (listView1.SelectedItems.Count > 0)
            {
                xFile = new XmlDocument();
                xFile.Load("settings.xml");

                XmlNode NodeRoot = xFile.SelectSingleNode("//locations");
                XmlNode NodeToFind = xFile.SelectSingleNode("//location[@station=\"" + listView1.SelectedItems[0].Tag.ToString() + "\"]");
                
                if (NodeToFind != null)
                {
                    MessageBox.Show("You are already subscribed to the weather for " + listView1.SelectedItems[0].Text, "Weathertastic", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                else
                {
                    XmlNode NewNode = xFile.CreateNode("element", "location", null) ;
                    //XmlNode NewNode = NodeRoot.create
                    //XmlElement el = NodeRoot.create

                    XmlAttribute stationAttribute = xFile.CreateAttribute("station");
                    stationAttribute.Value = listView1.SelectedItems[0].Tag.ToString();

                    XmlAttribute nameAttribute = xFile.CreateAttribute("name");
                    nameAttribute.Value = listView1.SelectedItems[0].Text;

                    XmlAttribute defaultAttribute = xFile.CreateAttribute("default");
                    defaultAttribute.Value = false.ToString();

                    NewNode.Attributes.Append(stationAttribute);

                    NewNode.Attributes.Append(nameAttribute);

                    NewNode.Attributes.Append(defaultAttribute);

                    NodeRoot.AppendChild(NewNode);
                    xFile.Save("settings.xml");

                    Close();
                }

                xFile = null;
            }
        }

        private void textSearch_TextChanged(object sender, EventArgs e)
        {

        }

        private void listView1_DoubleClick(object sender, EventArgs e)
        {
            SaveLocation();
            //Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void btnApply_Click(object sender, EventArgs e)
        {
            SaveLocation();
            //Close();
        }

        private void listView1_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
          
        }

        private void listView1_SelectedIndexChanged(object sender, EventArgs e)
        {
           
        }

        private void listView1_Click(object sender, EventArgs e)
        {
            if (listView1.SelectedItems.Count > 0)
                btnApply.Enabled = true;
            else
                btnApply.Enabled = false;
        }
    }
}